<?php
namespace app\pay\controller\common;

use think\Controller;

class DaifuApply extends Controller {
    /*
     * 客户向畅远管理后台发起代付申请
     * 将申请信息保存到model('PayBisApply')
     */
    public function apply($data, $resPayBis) {
        // 验证签名并
        $verSign = $data['signature'];
        unset($data['signature']);
        $md5key = $resPayBis->md5key;
        $data['signature'] = payChangyuanSign($data, $md5key); // 创建签名
        // 验证签名
        if($verSign == $data['signature']) {  
            // 代付申请数据处理
            return $this->applyHandle($data, $resPayBis);
        } else {
            // <畅远>签名验证失败
            return changyuanSignFalse();
        }
    }
    
    /*
     * 代付申请数据处理
     */
    private function applyHandle($data, $resPayBis) {
        $resPayDaifuApply = model('PayDaifuApply')->get(['mchnt_orderid' => $data['mchnt_orderid']]);
        if($resPayDaifuApply) {
            return retMsgFalse('出款订单号已存在'); 
        }
        $resPayPlatform = model('PayPlatform')->get(['id' => $resPayBis->platform_id]);
        // 代付手续费
        $daifuFee = $resPayBis->mchnt_daifu_fee + $resPayPlatform->daifu_fee;
        if(($data['amount'] + $daifuFee) <= $resPayBis->amount) {
            $payBisApplyData = array(
                'merchant_id'    => $data['merchant_id'],
                'mchnt_batchid'  => $data['mchnt_batchid'],
                'mchnt_orderid'  => $data['mchnt_orderid'],
                'amount'         => $data['amount'],
                'account_name'   => $data['account_name'],
                'account_number' => $data['account_number'],
                'bank_code'      => $data['bank_code'],
                'fee'            => $resPayBis->mchnt_daifu_fee + $resPayPlatform->daifu_fee,
                'is_agree'       => '0'
            );
            $resAddId = model('PayDaifuApply')->add($payBisApplyData); // 保存数据到数据库
            if($resAddId) {
                $amountAndFee = $data['amount'] + $resPayBis->mchnt_daifu_fee + $resPayPlatform->daifu_fee;
                $resUpdate = payBisAmount($resPayBis, $amountAndFee); // 更新 model('payBis') 相关金额
                if($resUpdate) {
                    $dataArr = array(
                        'merchant_id'   => $data['merchant_id'],
                        'mchnt_orderid' => $data['mchnt_orderid'],
                        'amount'        => $data['amount'],
                    );
                    return daifuApplyTrue($dataArr, $resPayBis->md5key);  // 代付请求结果返回给客户端  
                } else {
                    return retMsgFalse('代付请求失败'); 
                } 
            } else {
                return retMsgFalse('代付请求失败'); 
            }
        } else {
            return retMsgFalse('可用打款余额不足');
        }
    }
}

